package com.zhuliwei.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhuliwei.domain.ResponseResult;
import com.zhuliwei.domain.dto.ChatContentDto;
import com.zhuliwei.domain.entity.ChatContent;
import com.zhuliwei.domain.entity.User;
import com.zhuliwei.domain.vo.ChatContentVo;
import com.zhuliwei.domain.vo.PageVo;
import com.zhuliwei.enums.AppHttpCodeEnum;
import com.zhuliwei.mapper.ChatContentMapper;
import com.zhuliwei.mapper.UserMapper;
import com.zhuliwei.utils.BeanCopyUtils;
import com.zhuliwei.utils.WebUtils;
import io.swagger.annotations.Api;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 机器人聊天记录管理
 *
 * @author 朱力维
 * @since 2024-12-03 18:01:51
 */
@RestController
@RequestMapping("/content/chat")
@Api(tags = "机器人聊天记录", description = "聊天记录管理相关接口")
public class ChatController {
    /**
     * 服务对象
     */
    @Resource
    private ChatContentMapper chatContentMapper;

    @Resource
    private UserMapper userMapper;

    /**
     * 分页查询所有数据
     */
    @GetMapping("/list")
    @PreAuthorize("@ps.hasPermission('content:chat:list')")
    public ResponseResult selectAll(Integer pageNum, Integer pageSize, ChatContentDto chatDto) {
        User user = null;
        if (StringUtils.hasText(chatDto.getQuestion())) {
            LambdaQueryWrapper<User> lqwUser = new LambdaQueryWrapper();
            lqwUser.eq(User::getUserName, chatDto.getUserName());
            lqwUser.select(User::getId);
            user = userMapper.selectOne(lqwUser);
        }
        //分页查询
        LambdaQueryWrapper<ChatContent> lqw = new LambdaQueryWrapper();
        lqw.like(StringUtils.hasText(chatDto.getQuestion()), ChatContent::getQuestion, chatDto.getQuestion());
        lqw.eq(null != chatDto.getStatus(), ChatContent::getStatus, chatDto.getStatus());
        if (!ObjectUtils.isEmpty(user))
            lqw.eq(!ObjectUtils.isEmpty(user), ChatContent::getCreateBy, user.getId());
        // 拼接sql语句，将数据库的DateTime格式转换成Date格式进行比较
        lqw.apply(null != chatDto.getCreateTime(), "DATE(create_time) = {0}", chatDto.getCreateTime());
        lqw.orderByDesc(ChatContent::getCreateTime);
        Page<ChatContent> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        chatContentMapper.selectPage(page, lqw);
        List<ChatContent> chats = page.getRecords();
        List<ChatContentVo> chatVos = BeanCopyUtils.copyBeanList(chats, ChatContentVo.class);
        chatVos.forEach(chatVo -> {
            chatVo.setUserName(userMapper.selectById(chatVo.getCreateBy()).getUserName());
        });
        //封装数据返回
        PageVo pageVo = new PageVo(chatVos, page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/{id}")
    public ResponseResult selectOne(@PathVariable String id) {
        return ResponseResult.okResult(chatContentMapper.selectById(id));
    }

    /**
     * 删除数据
     *
     * @param ids 主键结合
     * @return 删除结果
     */
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ps.hasPermission('content:chat:delete')")
    public ResponseResult delete(@PathVariable List<String> ids) {
        return ResponseResult.okResult(chatContentMapper.deleteBatchIds(ids));
    }

    @GetMapping("/export")
    @PreAuthorize("@ps.hasPermission('content:chat:export')")
    public void export(HttpServletResponse response) {
        try {
            //设置下载文件的请求头
            WebUtils.setDownLoadHeader("机器人聊天记录.xlsx", response);
            //获取需要导出的数据
            List<ChatContent> chats = chatContentMapper.selectList(null);
            List<ChatContentVo> chatVos = BeanCopyUtils.copyBeanList(chats, ChatContentVo.class);
            chatVos.forEach(chatVo -> {
                chatVo.setUserName(userMapper.selectById(chatVo.getCreateBy()).getUserName());
            });
            //把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(), ChatContentVo.class).autoCloseStream(Boolean.FALSE).sheet("机器人聊天记录")
                    .doWrite(chatVos);
        } catch (Exception e) {
            //如果出现异常也要响应json
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }
}

